import { Service } from "egg";
const fs = require("fs");
/**
 * Test Service
 */
export default class User extends Service {
  /**
   * sayHi to you
   * @param user - your name
   */
  public async login(user: any) {
    console.log("login");
    const useItem = user?.user;
    let data: any = null;
    try {
      data = fs.readFileSync("./app/data/user.json",'utf8');
      let res = data.toString();
      const userList = JSON.parse(res);
      const isExist = userList.find((ele) => {
        return ele.username === useItem.username && ele.password === useItem.password;
        // return ele.email === useItem.email && ele.password === useItem.password;
      });
      if (isExist) {
        return {
          code: 200,
          msg: "success",
          data: {
            msg:'登录成功',
            token: Math.random().toFixed(10),
          },
        };
      }
      return {
        code: 10000,
        msg: "fail",
        data: "用户名或密码错误",
      };
    } catch (err) {
      console.log(err);
      return {
        code: 500,
        msg: "fail",
        data: "服务器异常",
      };
    }
  }
  public async register(user: any) {
    const useItem = user?.user;
    let data: any = null;
    try {
      data = fs.readFileSync("./app/data/user.json",'utf8');
      let res = data.toString();
      const userList = JSON.parse(res);
      const isExist = userList.find((ele) => {
        return ele.email === useItem.email ||ele.username === useItem.username
      });
      if (!isExist) {
        userList.push(useItem)
        console.log(JSON.stringify(userList))
        fs.writeFileSync("./app/data/user.json",JSON.stringify(userList),'utf8')
        return {
          code: 200,
          msg: "success",
          data: {
            msg:'注册成功'
          },
        };
      }
      return {
        code: 10000,
        msg: "fail",
        data:{
          msg:'用户名或密码已存在'
        }
      };
    } catch (err) {
      console.log(err);
      return {
        code: 500,
        msg: "fail",
        data:{
          msg: "服务器异常"
        }
      };
    }
  }
}
